package com.sys.app.web.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sys.app.entity.page.PageQuery;
import com.sys.app.entity.result.PageResultDTO;
import com.sys.app.entity.sql.PageSql;
import com.sys.app.entity.sys.SysAccount;
import com.sys.app.entity.result.ResultDTO;
import com.sys.app.entity.sys.myConstants;
import com.sys.app.entity.token.TokenUtil;
import com.sys.app.entity.util.SecrecyUtil;
import com.sys.app.entity.util.StringUtil;
import com.sys.app.service.page.IPageQueryService;
import com.sys.app.service.sys.ISysAccountService;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("sysAccount")
public class SysAccountContorller {
    private static Logger logger = LoggerFactory.getLogger(SysAccountContorller.class);
    private ISysAccountService iSysAccountService;
    private IPageQueryService iPageQueryService;
    public SysAccountContorller(ISysAccountService _iSysAccountService,
                                IPageQueryService iPageQueryService){
        this.iSysAccountService=_iSysAccountService;
        this.iPageQueryService=iPageQueryService;
    }


    /**
     * 主页首页
     * @return
     */
    @GetMapping("/index.do")
    public ModelAndView index(){
        ModelAndView modelAndView = new ModelAndView("main/sys/account/index");
        return modelAndView;
    }

    @PostMapping("/getAccountList.do")
    @ResponseBody
    public PageResultDTO<SysAccount> getAccountList(PageQuery pageQuery) throws InstantiationException, IllegalAccessException {
        //IPage<Map<String,Object>> page1=iPageQueryService.pageList(pageQuery,PageSql.getPageData());
        if(StringUtil.isEmpty(pageQuery.getOrder())) {
            pageQuery.setSort("createTime");
            pageQuery.setOrder("desc");
        }
        IPage<SysAccount> page1=iPageQueryService.pageList(pageQuery, PageSql.getAccountList(),SysAccount.class);
        return new PageResultDTO().result(page1);
    }

    /**
     * 新增/编辑
     * @return
     */
    @GetMapping("/edit.do")
    public ModelAndView  edit(Long id){
        ModelAndView modelAndView = new ModelAndView("main/sys/account/edit");
        if(id!=null&&id.longValue()>0) {
            QueryWrapper<SysAccount> queryWrapper = new QueryWrapper<SysAccount>();
            queryWrapper.eq("id", id);
            SysAccount entity = iSysAccountService.getOne(queryWrapper);
            modelAndView.addObject("entity", entity);
        }else{
            modelAndView.addObject("entity", new SysAccount());
        }
        return modelAndView;
    }

    @PostMapping("/save.do")
    @ResponseBody
    public ResultDTO save(SysAccount entity) {
        if(entity.getId()==null||entity.getId().longValue()==0){
            //新增,密码加密规则MD5(账号+密码+盐)转小写
            entity.setPassword(SecrecyUtil.UserPwdMd5(entity.getCode(),entity.getPassword(), myConstants.MD5_KEY));
            iSysAccountService.save(entity);
        }else{
            //编辑
            SysAccount userModel=iSysAccountService.getById(entity.getId());
            if(!entity.getPassword().equals(userModel.getPassword())){
                entity.setPassword(SecrecyUtil.UserPwdMd5(entity.getCode(),entity.getPassword(),myConstants.MD5_KEY));
            }
            iSysAccountService.updateById(entity);
        }
        return ResultDTO.ok().result("保存成功");
    }

    /**
     * 刷新jwt
     * @param request
     * @return
     */
    @PostMapping("/refToken.do")
    @ResponseBody
    public ResultDTO refToken(HttpServletRequest request, HttpSession session){
        if(myConstants.AUTHORIZATION_TYPE.equals("session")) {
            return ResultDTO.error().result("当前不需要token授权!");
        }
        Map<String,String> map=new HashMap<>();
        String token = request.getHeader(myConstants.AUTHORIZATION_KEY);
        token = StrUtil.replaceIgnoreCase(token, myConstants.JWT_PREFIX, Strings.EMPTY);
        boolean result= TokenUtil.verify(token);
        if(result) {
            SysAccount user = TokenUtil.getUserInfo(token);
            SysAccount userModel = iSysAccountService.getById(user.getId());
            //生成token
            String tokenNew=TokenUtil.sign(userModel);
            //获取token过期时间戳
            Long expireTime=TokenUtil.getJwtExpiresAt(tokenNew);
            map.put("expireTime",expireTime.toString());
            map.put("token", token);
            return ResultDTO.ok().result(map);
        }else{
            return ResultDTO.error().result("token验证失败!");
        }

    }
}
